package com.example.hotelback.service;

import com.example.hotelback.entity.Room;
import com.example.hotelback.mapper.RoomMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@Service
public class FileUploadService {

    @Autowired
    private RoomMapper roomMapper;

    public void upload(int id, MultipartFile photo, HttpServletRequest req) throws IOException { // 网络请求类（前端发过来一个req对象）
//            String path = req.getServletContext().getRealPath("/upload"); // 获取web服务器运行目录
            String path = "D:\\javaProject\\24暑实训\\imgs";
            System.out.println(path);
            saveFile(id, photo, path);
    }

    private void saveFile(int id, MultipartFile photo, String path) throws IOException {
        // 判断存储的目录是否存在，如果不存在则创建
        File dir = new File(path); // 定位目录位置
        if(!dir.exists()) { // upload目录
            dir.mkdir();
        }
        String fileName = System.currentTimeMillis() + photo.getOriginalFilename();
        File file = new File(path + "/" + fileName); // 定位文件
        photo.transferTo(file); // 把文件写入服务器目录

        Room room = roomMapper.selectById(id);
        room.setRoomImage(fileName);
        roomMapper.updateById(room);
    }


    public void getImage(String fileName, HttpServletResponse response) throws IOException {
        File file = new File("D:\\javaProject\\24暑实训\\imgs\\" + fileName);
        if (file.exists()) {
            FileInputStream fis = new FileInputStream(file);
            response.setContentType("image/jpg");
            OutputStream os = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
            os.close();
            fis.close();
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

}
